import {Injectable} from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse
} from '@angular/common/http';
import {finalize, tap, timeout, catchError} from 'rxjs/operators';
import {Observable, throwError} from 'rxjs';

import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';
import {environment} from '../../environments/environment';

/**
 * 拦截器，拦截所有http请求
 */

@Injectable()
export class WholeInterceptor implements HttpInterceptor {
  // 调试模式
  public deBug: boolean = !environment.production;

  public HOST = '';

  constructor(
    private router: Router,
    private message: NzMessageService,
  ) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let baseUrl = req.headers.get('baseUrl');

    // if (this.deBug) {
    //     // 本地代理 · 测试环境
    //     this.HOST = "/test";
    //     // 普普优品
    //     // this.HOST = '/ppyp';
    //     // 何日琛本地
    //     // this.HOST = '/hrc';
    //     // 本地代理 · 本地环境
    //     // this.HOST = "/loca"; // dongjun
    //     // this.HOST = "/loca2"; // liubing
    //     this.HOST = "/huangliubin"; // 黄刘滨
    //     // 本地代理 · 生成环境
    //     // this.HOST = "/i5";
    //     // this.HOST = "/i6";
    // }
    if (this.deBug) {
      // 本地切换默认商城api，不影响打包(替换本机地址调试)
      this.HOST = baseUrl ? baseUrl : environment.VALUE_KEY_URL;
    } else {
      // 打包(注意修改)
      this.HOST = baseUrl ? baseUrl : environment.VALUE_KEY_URL;
    }
    let url = req.url;

    // 判断是否加载本地json
    if (url.indexOf('.json') !== -1) {
      this.HOST = '';
    }

    url = this.HOST + url;

    req = req.clone({
      url
    });

    req = this.handleRequest(req);

    return next.handle(req).pipe(
      // timeout(15000),

      tap((event: any) => {
        // 请求成功
        if (event.status === 200) {
          // 业务处理：一些通用操作
          switch (event.body.code) {
            case -1: // 未登录状态码
              this.createMessage('error', '登录超时');
              localStorage.clear();
              this.router.navigate(['login'], {replaceUrl: true});
              break;
            case 500: // 未登录状态码
              this.createMessage('error', event.body.message);
              break;
          }
        }
      }),
      // 都会调用
      finalize(() => {

      }),

      // catchError((err: HttpErrorResponse) => {
      //     return throwError(new Error('请求超时'));
      // })
    );
  }

  // 请求参数处理
  handleRequest(req: any) {
    if (req.method.toUpperCase() === 'GET' && req.params.map.size) {
      for (let item of req.params.map.values()) {
        if (Object.prototype.toString.call(item[0]) === '[object String]') {
          item[0] = item[0].trim();
        }
      }
    } else if (req.method.toUpperCase() === 'POST') {
      for (let key in req.body) {
        if (Object.prototype.toString.call(req.body[key]) === '[object String]') {
          req.body[key] = req.body[key].trim();
        }
      }
    }

    req = req.clone({
      params: req.params
    })
    return req;
  }

  /**
   * 全局展示操作反馈信息
   * @param type 其他提示类型 success:成功 error:失败 warning:警告
   */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }
}
